package com.soms.filter;

import cn.hutool.json.JSONUtil;
import com.soms.constants.LoginConst;
import com.soms.util.HttpResponseUtil;
import com.soms.util.ResultUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// 拦截所有的/server/的servlet
@WebFilter(value = {"/server/*"})
public class AuthFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute(LoginConst.USER_CODE) == null) {
            // 响应401
            HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.unAuthenticated()));
        } else {
            // 登录了
            chain.doFilter(request, response);
        }
    }
}
